﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Hzexe.Wechat.SharpSDK.Message.JSONData.Support
{
    /// <summary>
    /// 令牌数据
    /// </summary>
    [Serializable]
    class AccessTokenResult : ResultBase
    {
        /// <summary>
        /// 令牌
        /// </summary>
        public string access_token { get; set; }
        /// <summary>
        /// 过期时间
        /// </summary>
        public int expires_in { get; set; }

        private static string _AccessToken;
        /// <summary>
        /// 计时器,用来更新AccessToken
        /// </summary>
        /// <remarks>正常情况下access_token有效期为7200秒，重复获取将导致上次获取的access_token失效</remarks>
        private static System.Timers.Timer tmr = new System.Timers.Timer(7000000);


        static AccessTokenResult()
        {
            tmr.Elapsed += (a, b) => refreshAccessToken();
            tmr.Enabled = true;
        }

        /// <summary>
        /// 获取用户的access_token
        /// </summary>
        public static string AccessToken
        {
            get {
                if (!string.IsNullOrEmpty(_AccessToken))
                    refreshAccessToken();
                return AccessTokenResult._AccessToken;
            }
        }


        private static void refreshAccessToken()
        {
            var url=string.Format(
@"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={1}&secret={0}",
                Properties.Settings.Default.appid,
                Properties.Settings.Default.secret
                );
            
            
            string jsonstring = @"{""errcode"":40013,""errmsg"":""http request error""}";
            WebClient wc = new WebClient();
            wc.Encoding = System.Text.Encoding.UTF8;
            try
            {
                jsonstring = wc.DownloadString(url);
            }
            catch (Exception ex)
            {
                log.Warn("请求远程服务器" + url +"失败",ex);
            }
            finally
            {
                wc.Dispose();
            }

            var b= Newtonsoft.Json.JsonConvert.DeserializeObject<AccessTokenResult>(jsonstring);
            if(b.errcode==0)
            {
               _AccessToken=b.access_token; 

            }
        }
    }
}
